#include "UARTtoCAN.h"
#include "string.h"
#include "bsp_uart.h"
#include "bsp_can.h"

void UARTtoCAN(CAN_HandleTypeDef *hcan, uint32_t CAN_ID, uint8_t *Rx_Buf)
{
    char *index;
    char BufL;
    char BufH;
    uint8_t data[8];
    uint8_t i = 0;

    index = strstr((char *)Rx_Buf, "0x");

    while (index != NULL)
    {
        index += 2;

        if (*index >= '0' && *index <= '9')
        {
            BufH = *index - 48;
        }
        else if (*index >= 'A' && *index <= 'F')
        {
            BufH = *index - 55;
        }
        else
        {
            UART_Print("error\n");
            return;
        }

        if (*(index + 1) >= '0' && *(index + 1) <= '9')
        {
            BufL = *(index + 1) - 48;
        }
        else if (*(index + 1) >= 'A' && *(index + 1) <= 'F')
        {
            BufL = *(index + 1) - 55;
        }
        else
        {
            UART_Print("error\n");
            return;
        }

        data[i] = (BufH << 4) | BufL;

        index = strstr(index, "0x");
        i++;
    }

    CAN_Transmit(hcan, CAN_ID, data);
    // UART_Print("0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X\n", data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7]);
}